<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

/**
 * Think 标准模式公共函数库
 * @category   Think
 * @package  Common
 * @author   liu21st <liu21st@gmail.com>
 */

/**
 * 错误输出
 * @param mixed $error 错误
 * @return void
 */
function halt($error) {
    $e = array();
    if (APP_DEBUG) {
        //调试模式下输出错误信息
        if (!is_array($error)) {
            $trace          = debug_backtrace();
            $e['message']   = $error;
            $e['file']      = $trace[0]['file'];
            $e['line']      = $trace[0]['line'];
            ob_start();
            debug_print_backtrace();
            $e['trace']     = ob_get_clean();
        } else {
            $e              = $error;
        }
    } else {
        //否则定向到错误页面
        $error_page         = C('ERROR_PAGE');
        if (!empty($error_page)) {
            redirect($error_page);
        } else {
            if (C('SHOW_ERROR_MSG'))
                $e['message'] = is_array($error) ? $error['message'] : $error;
            else
                $e['message'] = C('ERROR_MESSAGE');
        }
    }
    // 包含异常页面模板
    include C('TMPL_EXCEPTION_FILE');
    exit;
}

/**
 * 自定义异常处理
 * @param string $msg 异常消息
 * @param string $type 异常类型 默认为ThinkException
 * @param integer $code 异常代码 默认为0
 * @return void
 */
function throw_exception($msg, $type='ThinkException', $code=0) {
    if (class_exists($type, false))
        throw new $type($msg, $code);
    else
        halt($msg);        // 异常类型不存在则输出错误信息字串
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dump($var, $echo=true, $label=null, $strict=true) {
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    }else
        return $output;
}

/**
 * 404处理 
 * 调试模式会抛异常 
 * 部署模式下面传入url参数可以指定跳转页面，否则发送404信息
 * @param string $msg 提示信息
 * @param string $url 跳转URL地址
 * @return void
 */
function _404($msg='',$url='') {
    APP_DEBUG && throw_exception($msg);
    if($msg && C('LOG_EXCEPTION_RECORD')) Log::write($msg);
    if(empty($url) && C('URL_404_REDIRECT')) {
        $url    =   C('URL_404_REDIRECT');
    }
    if($url) {
        redirect($url);
    }else{
        send_http_status(404);
        exit;
    }
}

/**
 * 设置当前页面的布局
 * @param string|false $layout 布局名称 为false的时候表示关闭布局
 * @return void
 */
function layout($layout) {
    if(false !== $layout) {
        // 开启布局
        C('LAYOUT_ON',true);
        if(is_string($layout)) { // 设置新的布局模板
            C('LAYOUT_NAME',$layout);
        }
    }else{// 临时关闭布局
        C('LAYOUT_ON',false);
    }
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
 * @param boolean $domain 是否显示域名
 * @return string
 */
function U($url='',$vars='',$suffix=true,$redirect=false,$domain=true, $admin=false) {
    // 解析URL
    $info   =  parse_url($url);
    $url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
	$isDirection = substr($url, -1) == '/';
	
    if(isset($info['fragment'])) { // 解析锚点
        $anchor =   $info['fragment'];
        if(false !== strpos($anchor,'?')) { // 解析参数
            list($anchor,$info['query']) = explode('?',$anchor,2);
        }        
        if(false !== strpos($anchor,'@')) { // 解析域名
            list($anchor,$host)    =   explode('@',$anchor, 2);
        }
    }elseif(false !== strpos($url,'@')) { // 解析域名
        list($url,$host)    =   explode('@',$info['path'], 2);
    }
	
	
    // 解析子域名
    if(isset($host)) {
        $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
    }elseif($domain===true){
        $domain = $_SERVER['HTTP_HOST'];
        if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
            $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
            // '子域名'=>array('项目[/分组]');
            foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
                if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
                    $domain = $key.strstr($domain,'.'); // 生成对应子域名
                    $url    =  substr_replace($url,'',0,strlen($rule[0]));
                    break;
                }
            }
        }
    }

    // 解析参数
    if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
        parse_str($vars,$vars);
    }elseif(!is_array($vars)){
        $vars = array();
    }
    if(isset($info['query'])) { // 解析地址里面参数 合并到vars
        parse_str($info['query'],$params);
        $vars = array_merge($params,$vars);
    }
   
    // URL组装
    $depr = C('URL_PATHINFO_DEPR');
    if($url) {
        if(0=== strpos($url,'/')) {// 定义路由
            $route      =   true;
            $url        =   substr($url,1);
            if('/' != $depr) {
                $url    =   str_replace('/',$depr,$url);
            }
        }else{
            if('/' != $depr) { // 安全替换
                $url    =   str_replace('/',$depr,$url);
            }
            // 解析分组、模块和操作
            $url        =   trim($url,$depr);
            $path       =   explode($depr,$url);
            $var        =   array();
            $var[C('VAR_ACTION')]       =   !empty($path)?array_pop($path):ACTION_NAME;
            $var[C('VAR_MODULE')]       =   !empty($path)?array_pop($path):MODULE_NAME;
            if($maps = C('URL_ACTION_MAP')) {
                if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
                    $maps    =   $maps[strtolower($var[C('VAR_MODULE')])];
                    if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
                        $var[C('VAR_ACTION')] = $action;
                    }
                }
            }
            if($maps = C('URL_MODULE_MAP')) {
                if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
                    $var[C('VAR_MODULE')] = $module;
                }
            }            
            if(C('URL_CASE_INSENSITIVE')) {
                $var[C('VAR_MODULE')]   =   parse_name($var[C('VAR_MODULE')]);
            }
            if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
                if(!empty($path)) {
                    $group                  =   array_pop($path);
                    $var[C('VAR_GROUP')]    =   $group;
                }else{
                    if(GROUP_NAME != C('DEFAULT_GROUP')) {
                        $var[C('VAR_GROUP')]=   GROUP_NAME;
                    }
                }
                if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
                    $var[C('VAR_GROUP')]    =  strtolower($var[C('VAR_GROUP')]);
                }
            }
        }
    }
    if(C('URL_MODEL') == 0) { // 普通模式URL转换
        $url        =   __APP__.'?'.http_build_query(array_reverse($var));
        if(!empty($vars)) {
            $vars   =   urldecode(http_build_query($vars));
            $url   .=   '&'.$vars;
        }
    }else{ // PATHINFO模式或者兼容URL模式
	
        if(isset($route)) {
            $url    =   __APP__.'/'.rtrim($url,$depr);
        }else{
            $url    =   __APP__.'/'.implode($depr,array_reverse($var));
        }
		if($admin){
			$url = str_replace( __APP__ , '', $url);	
		}
		
        if(!empty($vars)) { // 添加参数
            foreach ($vars as $var => $val){
                if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
            }                
        }
		
        if($suffix) {
            $suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
            if($pos = strpos($suffix, '|')){
                $suffix = substr($suffix, 0, $pos);
            }
            
			if(empty($vars) && $isDirection && '/' != substr($url,-1)){
                $url  .=  '/';
            }
			
			if($suffix && '/' != substr($url,-1)){
                $url  .=  '.'.ltrim($suffix,'.');
            }
			
        }
		
    }

    if(isset($anchor)){
        $url  .= '#'.$anchor;
    }
    if($domain) {
        $url   =  (is_ssl()?'https://':'http://').$domain.$url;
    }
	
	
    if($redirect) // 直接跳转URL
        redirect($url);
    else
        return $url;
}

/**
 * 渲染输出Widget
 * @param string $name Widget名称
 * @param array $data 传入的参数
 * @param boolean $return 是否返回内容 
 * @param string $path Widget所在路径
 * @return void
 */
function W($name, $data=array(), $return=false,$path='') {
    $class      =   $name . 'Widget';
    $path       =   empty($path) ? BASE_LIB_PATH : $path;
    require_cache($path . 'Widget/' . $class . '.class.php');
    if (!class_exists($class))
        throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
    $widget     =   Think::instance($class);
    $content    =   $widget->render($data);
    if ($return)
        return $content;
    else
        echo $content;
}

/**
 * 过滤器方法 引用传值
 * @param string $name 过滤器名称
 * @param string $content 要过滤的内容
 * @return void
 */
function filter($name, &$content) {
    $class      =   $name . 'Filter';
    require_cache(BASE_LIB_PATH . 'Filter/' . $class . '.class.php');
    $filter     =   new $class();
    $content    =   $filter->run($content);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl() {
    if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
        return true;
    }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
        return true;
    }
    return false;
}

/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time=0, $msg='') {
    //多行URL地址支持
    $url        = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg))
        $msg    = "系统将在{$time}秒之后自动跳转到{$url}！";
    if (!headers_sent()) {
        // redirect
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    } else {
        $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0)
            $str .= $msg;
        exit($str);
    }
}

/**
 * 缓存管理
 * @param mixed $name 缓存名称，如果为数组表示进行缓存设置
 * @param mixed $value 缓存值
 * @param mixed $options 缓存参数
 * @return mixed
 */
function S($name,$value='',$options=null) {
    static $cache   =   '';
    if(is_array($options) && empty($cache)){
        // 缓存操作的同时初始化
        $type       =   isset($options['type'])?$options['type']:'';
        $cache      =   Cache::getInstance($type,$options);
    }elseif(is_array($name)) { // 缓存初始化
        $type       =   isset($name['type'])?$name['type']:'';
        $cache      =   Cache::getInstance($type,$name);
        return $cache;
    }elseif(empty($cache)) { // 自动初始化
        $cache      =   Cache::getInstance();
    }
    if(''=== $value){ // 获取缓存
        return $cache->get($name);
    }elseif(is_null($value)) { // 删除缓存
        return $cache->rm($name);
    }else { // 缓存数据
        if(is_array($options)) {
            $expire     =   isset($options['expire'])?$options['expire']:NULL;
        }else{
            $expire     =   is_numeric($options)?$options:NULL;
        }
        return $cache->set($name, $value, $expire);
    }
}
// S方法的别名 已经废除 不再建议使用
function cache($name,$value='',$options=null){
    return S($name,$value,$options);
}

/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
function F($name, $value='', $path=DATA_PATH) {
    static $_cache  = array();
    $filename       = $path . $name . '.php';
    if ('' !== $value) {
        if (is_null($value)) {
            // 删除缓存
            return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
        } else {
            // 缓存数据
            $dir            =   dirname($filename);
            // 目录不存在则创建
            if (!is_dir($dir))
                mkdir($dir,0755,true);
            $_cache[$name]  =   $value;
            return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
        }
    }
    if (isset($_cache[$name]))
        return $_cache[$name];
    // 获取缓存数据
    if (is_file($filename)) {
        $value          =   include $filename;
        $_cache[$name]  =   $value;
    } else {
        $value          =   false;
    }
    return $value;
}

/**
 * 取得对象实例 支持调用类的静态方法
 * @param string $name 类名
 * @param string $method 方法名，如果为空则返回实例化对象
 * @param array $args 调用参数
 * @return object
 */
function get_instance_of($name, $method='', $args=array()) {
    static $_instance = array();
    $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
    if (!isset($_instance[$identify])) {
        if (class_exists($name)) {
            $o = new $name();
            if (method_exists($o, $method)) {
                if (!empty($args)) {
                    $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
                } else {
                    $_instance[$identify] = $o->$method();
                }
            }
            else
                $_instance[$identify] = $o;
        }
        else
            halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
    }
    return $_instance[$identify];
}

/**
 * 根据PHP各种类型变量生成唯一标识号
 * @param mixed $mix 变量
 * @return string
 */
function to_guid_string($mix) {
    if (is_object($mix) && function_exists('spl_object_hash')) {
        return spl_object_hash($mix);
    } elseif (is_resource($mix)) {
        $mix = get_resource_type($mix) . strval($mix);
    } else {
        $mix = serialize($mix);
    }
    return md5($mix);
}

/**
 * XML编码
 * @param mixed $data 数据
 * @param string $root 根节点名
 * @param string $item 数字索引的子节点名
 * @param string $attr 根节点属性
 * @param string $id   数字索引子节点key转换的属性名
 * @param string $encoding 数据编码
 * @return string
 */
function xml_encode($data, $root='think', $item='item', $attr='', $id='id', $encoding='utf-8') {
    if(is_array($attr)){
        $_attr = array();
        foreach ($attr as $key => $value) {
            $_attr[] = "{$key}=\"{$value}\"";
        }
        $attr = implode(' ', $_attr);
    }
    $attr   = trim($attr);
    $attr   = empty($attr) ? '' : " {$attr}";
    $xml    = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
    $xml   .= "<{$root}{$attr}>";
    $xml   .= data_to_xml($data, $item, $id);
    $xml   .= "</{$root}>";
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed  $data 数据
 * @param string $item 数字索引时的节点名称
 * @param string $id   数字索引key转换为的属性名
 * @return string
 */
function data_to_xml($data, $item='item', $id='id') {
    $xml = $attr = '';
    foreach ($data as $key => $val) {
        if(is_numeric($key)){
            $id && $attr = " {$id}=\"{$key}\"";
            $key  = $item;
        }
        $xml    .=  "<{$key}{$attr}>";
        $xml    .=  (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val;
        $xml    .=  "</{$key}>";
    }
    return $xml;
}

/**
 * session管理函数
 * @param string|array $name session名称 如果为数组则表示进行session设置
 * @param mixed $value session值
 * @return mixed
 */
function session($name,$value='') {
    $prefix   =  C('SESSION_PREFIX');
    if(is_array($name)) { // session初始化 在session_start 之前调用
        if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
        if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){
            session_id($_REQUEST[C('VAR_SESSION_ID')]);
        }elseif(isset($name['id'])) {
            session_id($name['id']);
        }
        ini_set('session.auto_start', 0);
        if(isset($name['name']))            session_name($name['name']);
        if(isset($name['path']))            session_save_path($name['path']);
        if(isset($name['domain']))          ini_set('session.cookie_domain', $name['domain']);
        if(isset($name['expire']))          ini_set('session.gc_maxlifetime', $name['expire']);
        if(isset($name['use_trans_sid']))   ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
        if(isset($name['use_cookies']))     ini_set('session.use_cookies', $name['use_cookies']?1:0);
        if(isset($name['cache_limiter']))   session_cache_limiter($name['cache_limiter']);
        if(isset($name['cache_expire']))    session_cache_expire($name['cache_expire']);
        if(isset($name['type']))            C('SESSION_TYPE',$name['type']);
        if(C('SESSION_TYPE')) { // 读取session驱动
            $class      = 'Session'. ucwords(strtolower(C('SESSION_TYPE')));
            // 检查驱动类
            if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) {
                $hander = new $class();
                $hander->execute();
            }else {
                // 类没有定义
                throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class);
            }
        }
        // 启动session
        if(C('SESSION_AUTO_START'))  session_start();
    }elseif('' === $value){ 
        if(0===strpos($name,'[')) { // session 操作
            if('[pause]'==$name){ // 暂停session
                session_write_close();
            }elseif('[start]'==$name){ // 启动session
                session_start();
            }elseif('[destroy]'==$name){ // 销毁session
                $_SESSION =  array();
                session_unset();
                session_destroy();
            }elseif('[regenerate]'==$name){ // 重新生成id
                session_regenerate_id();
            }
        }elseif(0===strpos($name,'?')){ // 检查session
            $name   =  substr($name,1);
            if(strpos($name,'.')){ // 支持数组
                list($name1,$name2) =   explode('.',$name);
                return $prefix?isset($_SESSION[$prefix][$name1][$name2]):isset($_SESSION[$name1][$name2]);
            }else{
                return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]);
            }
        }elseif(is_null($name)){ // 清空session
            if($prefix) {
                unset($_SESSION[$prefix]);
            }else{
                $_SESSION = array();
            }
        }elseif($prefix){ // 获取session
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$prefix][$name1][$name2])?$_SESSION[$prefix][$name1][$name2]:null;  
            }else{
                return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;                
            }            
        }else{
            if(strpos($name,'.')){
                list($name1,$name2) =   explode('.',$name);
                return isset($_SESSION[$name1][$name2])?$_SESSION[$name1][$name2]:null;  
            }else{
                return isset($_SESSION[$name])?$_SESSION[$name]:null;
            }            
        }
    }elseif(is_null($value)){ // 删除session
        if($prefix){
            unset($_SESSION[$prefix][$name]);
        }else{
            unset($_SESSION[$name]);
        }
    }else{ // 设置session
        if($prefix){
            if (!is_array($_SESSION[$prefix])) {
                $_SESSION[$prefix] = array();
            }
            $_SESSION[$prefix][$name]   =  $value;
        }else{
            $_SESSION[$name]  =  $value;
        }
    }
}

/**
 * Cookie 设置、获取、删除
 * @param string $name cookie名称
 * @param mixed $value cookie值
 * @param mixed $options cookie参数
 * @return mixed
 */
function cookie($name, $value='', $option=null) {
    // 默认设置
    $config = array(
        'prefix'    =>  C('COOKIE_PREFIX'), // cookie 名称前缀
        'expire'    =>  C('COOKIE_EXPIRE'), // cookie 保存时间
        'path'      =>  C('COOKIE_PATH'), // cookie 保存路径
        'domain'    =>  C('COOKIE_DOMAIN'), // cookie 有效域名
    );
    // 参数设置(会覆盖黙认设置)
    if (!is_null($option)) {
        if (is_numeric($option))
            $option = array('expire' => $option);
        elseif (is_string($option))
            parse_str($option, $option);
        $config     = array_merge($config, array_change_key_case($option));
    }
    // 清除指定前缀的所有cookie
    if (is_null($name)) {
        if (empty($_COOKIE))
            return;
        // 要删除的cookie前缀，不指定则删除config设置的指定前缀
        $prefix = empty($value) ? $config['prefix'] : $value;
        if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
            foreach ($_COOKIE as $key => $val) {
                if (0 === stripos($key, $prefix)) {
                    setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
                    unset($_COOKIE[$key]);
                }
            }
        }
        return;
    }
    $name = $config['prefix'] . $name;
    if ('' === $value) {
        if(isset($_COOKIE[$name])){
            $value =    $_COOKIE[$name];
            if(0===strpos($value,'think:')){
                $value  =   substr($value,6);
                return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true));
            }else{
                return $value;
            }
        }else{
            return null;
        }
    } else {
        if (is_null($value)) {
            setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
            unset($_COOKIE[$name]); // 删除指定cookie
        } else {
            // 设置cookie
            if(is_array($value)){
                $value  = 'think:'.json_encode(array_map('urlencode',$value));
            }
            $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
            setcookie($name, $value, $expire, $config['path'], $config['domain']);
            $_COOKIE[$name] = $value;
        }
    }
}

/**
 * 加载动态扩展文件
 * @return void
 */
function load_ext_file() {
    // 加载自定义外部文件
    if(C('LOAD_EXT_FILE')) {
        $files      =  explode(',',C('LOAD_EXT_FILE'));
        foreach ($files as $file){
            $file   = COMMON_PATH.$file.'.php';
            if(is_file($file)) include $file;
        }
    }
    // 加载自定义的动态配置文件
    if(C('LOAD_EXT_CONFIG')) {
        $configs    =  C('LOAD_EXT_CONFIG');
        if(is_string($configs)) $configs =  explode(',',$configs);
        foreach ($configs as $key=>$config){
            $file   = CONF_PATH.$config.'.php';
            if(is_file($file)) {
                is_numeric($key)?C(include $file):C($key,include $file);
            }
        }
    }
}

function dateLocalFormat($time) { 
	$rtime = date("Y-m-d",$time); 
	$htime = date("H:i",$time); 
	$time = time() - $time; 
	if ($time < 60) { 
		$str = '刚刚'; 
	} elseif ($time < 60 * 60) { 
		$min = floor($time/60); 
		$str = $min.'分钟前'; 
	} elseif ($time < 60 * 60 * 24) { 
		$h = floor($time/(60*60)); 
		$str = $h.'小时前'; 
	} elseif ($time < 60 * 60 * 24 * 3) { 
		$d = floor($time/(60*60*24)); 
		if($d==1) 
			//$str = '昨天 '.$rtime; 
			$str = '昨天';
		else 
			//$str = '前天 '.$rtime; 
			$str = '前天';
	} else { 
		$str = $rtime; 
	} 
	return $str; 
}

function stringToLocalFormat($string) { 
	$time    = strtotime($string);
	$rtime   = date("m-d",$time); 
	$nowTime = time(); 
	
	$d1 = floor(($time)/(60*60*24)); 
	$d2 = floor(($nowTime)/(60*60*24)); 
	
	if($d2 == $d1){
		$str = '今天'; 	
	}else if($d2 > $d1){
		if($d2 - $d1 >= 3){
			$str = $rtime; 	
		}else if($d2 - $d1 >=2){
			$str = '前天'; 	
		}else if($d2 - $d1 >= 1){
			$str = '昨天'; 	
		}
	}else if($d2 < $d1){
		if($d1 - $d2 >= 3){
			$str = $rtime; 	
		}else if($d1 - $d2 >= 2){
			$str = '后天'; 	
		}else if($d1 - $d2 >= 1){
			$str = '明天'; 	
		}
	}
	
	return $str; 
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
	$type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',
        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ', // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',
        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}

// 过滤表单中的表达式
function think_filter(&$value){
    // TODO 其他安全过滤

    // 过滤查询特殊字符
    if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|LIKE|NOTLIKE|NOTBETWEEN|NOT BETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){
        $value .= ' ';
    }
}

//  打印函数
function P($str, $end = true){
	echo '<pre>';
	print_r($str);
	echo '</pre>';
	
	
	if($end){
		exit;	
	}
}

/**
 * 上传
*/
function upload($files = '', $savePath = '', $uploadType = array('jpg', 'gif', 'png', 'jpeg'), $autoSub = true){
	if(C('UPLOAD_TYPE') == 'qiniu'){
		$err['code'] = 1;
		if(is_array($files)){
			$err['message'] = uploadQiniu($files);
		}else{
			$err['message'] = uploadQiniu();
		}
		return $err;
	}else{
		if(!empty($_FILES[$files]['name'])){
			import('ORG.Net.UploadFile');
			$upload 		   	   = new UploadFile();
			$upload->allowExts 	   = $uploadType;
			$upload->savePath  	   = '.'.$savePath;
			$upload->uploadReplace = true;
			$upload->autoSub 	   = $autoSub;
			$upload->subType 	   = 'date';
			$upload->saveRule 	   = 'uniqid';
		
			if(!$upload->uploadOne($_FILES[$files])) {
				$err['code'] = 0;
				$err['message'] = $upload->getErrorMsg();
			}else{
				$err['code'] = 1;
				$err['message'] = $upload->getUploadFileInfo();
			}
			
			return $err;
		}
	}
	return false;
}

/**多文件上传*/
function uploadMore($files, $savePath, $uploadType = array('jpg', 'gif', 'png', 'jpeg'), $autoSub = true){
    $_FILES = array($files=>$_FILES[$files]);
    
    if(count($_FILES[$files]['name'])){
        
        import('ORG.Net.UploadFile');
        $upload                = new UploadFile();
        
        $upload->allowExts     = $uploadType;
        if(C('ROOT_PATH')==''){
            $upload->savePath      = '.'.$savePath;
        }else{
            $upload->savePath      = '.'.str_replace(C('ROOT_PATH'), '', $savePath);
        }
        
        $upload->uploadReplace = true;
        $upload->autoSub       = $autoSub;
        $upload->subType       = 'date';
    
        if(!$upload->upload()) {
            $err['code'] = 0;
            $err['message'] = $upload->getErrorMsg();
        }else{
            $err['code'] = 1;
            $err['message'] = $upload->getUploadFileInfo();
        }
        return $err;
    }
    return false;
}

/**
* 设置分类模型的链接
* @param $routeInfo 分类模型信息
* @param $domain 是否加上域名 
*/
function setCateUrl($code, $cateInfo, $domain = true){  
  $returnUrl = '';
  $code = strtolower($code);
  switch($code){
	case 'newscate':
		$returnUrl = U('/news/c'.$cateInfo['id'], '', true, false, true, true);
	break;
	case 'websitescate':
		$returnUrl = U('/websites/c'.$cateInfo['id'], '', true, false, true, true);
	break;
  }
  
  return $returnUrl;
}

/**
* 设置详情页url
*/
//$url='',$vars='',$suffix=true,$redirect=false,$domain=true
function setViewUrl($code, $info){
  $returnUrl = '';
  $code = strtolower($code);
  switch($code){
	case 'article':
		$returnUrl = U('/article/'.$info['id'], '', true, false, true, true);
	break;
	case 'about':
		$returnUrl = U('/about/'.$info['id'], '', true, false, true, true);
	break;
	case 'site':
		$returnUrl = U('/siteinfo/'.str_replace('.', '_', $info['domain']), '', true, false, true, true);
	break;
  }
  
  return $returnUrl;
}

/*
* 构造网站筛选url
	c: 分类
	x: 省份
	y: 城市
	p: 分页
http://localhost/websites/c1x2y3p2.html
*/
function buildFilterUrl($baseUrl, $c, $x, $y, $p){
	return $baseUrl.sprintf('%s%s%s%s', $c, $x, $y, $p);
}


/**
* 中文截取函数
*/
function mbsubstr($str, $start=0, $length, $suffix=true, $charset="utf-8") {
	if(function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	elseif(function_exists('iconv_substr')) {
		$slice = iconv_substr($str,$start,$length,$charset);
	}else{
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
	}
	
	if(strlen($str) > strlen($slice)){
		return $suffix ? $slice.'...' : $slice;
	}else{
		return $slice;
	}
}

/**
* 删除editor里面的图片
* @param text content 内容
* @return null
*/
function delEditorImage($content){
	$content = htmlspecialchars_decode($content);

	$allImg = $repImg = array();
	preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/', $content, $allImg);
	foreach($allImg[1] as $key=>$val){
		if( !preg_match('/^http:\/\/[a-zA-Z0-9]+/', $val) && !stripos($val, 'Public/images')){
			@unlink('.'.$val);
		}else if(substr_count($val, C('Qiniu.domain'))){//看看是不是七牛的。
			delImage($val);
		}
	}
}

/**
* 删除图片
* @param string key
* @param string image
*/
/*function delImage($key, $image){
    $dic = C('ROOT_PATH')  == '' ? '.' : '';
    switch($key){
        case 'ad':
            $savePath =$dic.C('TMPL_PARSE_STRING.__UPLOADAD__');
        break;
        case 'article':
            $savePath =$dic.C('TMPL_PARSE_STRING.__UPLOADARTICLE__');
        break;
    }
    $dirName = substr($image, 0, strrpos($image, '/'));
    $fileName = substr($image, strrpos($image, '/')+1);
    @unlink($savePath.$image); //删除原图
    $image = $savePath.$dirName.'/*'.$fileName;
    $list = glob($image);
    foreach($list as $val){
        @unlink($val);
    }
}*/

/**
* 过滤用户名
*/
function formateUsername($username){
	return empty($username) ? '匿名' : substr($username, 0, strpos($username, '@'));	
}

/**
* 判断内容中是否有网址
*/
function hasWebsite($content){
    return substr_count($content, 'http://') || substr_count($content, 'https://'); 
}

/**
* 设置密码
*/
function setPassword($password, $hash=''){
	return md5(md5($password).$hash);	
}

/**
* 获取内容冗余
**/
function getSubContent($content){
	return mbsubstr(str_replace(array("\r", "\n", "\r", "\r\n", ' ', '	'), '', strip_tags($content)), 0 , 150);	
}


/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashesDeep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashesDeep', $value) : addslashes($value);
    }
}
/**
 * 递归方式的对变量中的特殊字符去除转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function stripslashesDeep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('stripslashesDeep', $value) : stripslashes($value);
    }
} 

/**
* 文件上传到7牛
*/
function uploadQiniu($allowUrls = false){
	import('ORG.Net.Upload');

	$upload = new Upload(array('driverType'=>'Qiniu'), C('Qiniu'));// 实例化上传类
	//$upload->mimes = array('jpg'); //允许上传的类型
	
	// 上传文件
	if(!empty($allowUrls)){
		$info = $upload->allowUrlToServer($allowUrls);
	}else{
		$info = $upload->upload();
	}
	return $info;
}

/**
* 删除文件上传到7牛
*/
function delImage($images = ''){
	if(empty($images)){
		return false;
	}else{
		import('ORG.Net.Upload');
		$upload = new Upload(array('driverType'=>'Qiniu'), C('Qiniu'));// 实例化上传类
		
		//获取img路径
		if(is_array($images)){
			foreach($images as $img){
				if(substr_count($img, 'http://') || substr_count($img, 'https://')){
					$imgPath = pathinfo($img);
					$imgUrlPath = substr($imgPath['dirname'], strpos($images, '/',strpos($images,'://')+3)+1);
					$img = urldecode($imgUrlPath.'/'.$imgPath['basename']);
					
					$upload->deleteFile($img);
				}
			}
			return true;
		}else{
			if(substr_count($images, 'http://') || substr_count($images, 'https://')){
				$imgPath = pathinfo($images);
				$imgUrlPath = substr($imgPath['dirname'], strpos($images, '/',strpos($images,'://')+3)+1);
				$img = urldecode($imgUrlPath.'/'.$imgPath['basename']);
			}
			return $upload->deleteFile($img);
		}
	}
}

/**
* 编辑器文件上传到7牛
*/
function uploadEditor($formFileName = '', $savePath = ''){
	import('ORG.Net.JSON');
	header('Content-type: text/html; charset=UTF-8');
	$json = new JSON();
	if(empty($formFileName) || empty($savePath)){echo $json->encode(array('error' => 1, 'message' => '参数错误'));exit;}
	
	// 上传文件
	$info = upload($formFileName, $savePath);
	if(!$info) {// 上传错误提示错误信息
		echo $json->encode(array('error' => 1, 'message' => $info));
	}else{// 上传成功
		if(C('UPLOAD_TYPE') == 'qiniu'){
			echo $json->encode(array('error' => 0, 'url'=>urldecode($info['message']['imgFile']['url']), 'message' => $info['message']['imgFile']['name']));
		}else{
			echo $json->encode(array('error' => 0, 'url'=>urldecode($info['message'][0]['savepath'].$info['message'][0]['savename']), 'message' => $info['message'][0]['savename']));
		}
	}	
	exit;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function formatBytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}


/**
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 * @return string
 */
function randString($len=6,$type='',$addChars='') {
	$str ='';
	switch($type) {
		case 0:
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
			break;
		case 1:
			$chars= str_repeat('0123456789',3);
			break;
		case 2:
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
			break;
		case 3:
			$chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
			break;
		 default :
			// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
			$chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
			break;
	}
	if($len>10 ) {//位数过长重复字符串一定次数
		$chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
	}
	$chars   =   str_shuffle($chars);
		$str     =   substr($chars,0,$len);
	return $str;
}

/*
* 获得星星
*/
function getStar($starCount=0,$starPeople=0){
	return @ceil($starCount/$starPeople);
}

/**
* 判断是否为移动设备访问
*/
function isMobile(){
	$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
	$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile)/i";
	if(substr($_SERVER['HTTP_HOST'],0,2) == 'm.' || ($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
	{
		return true;
	}
	
	return false;
}

/**
* 验证是否是手机号码
*/
function isTel($tel){
	if(preg_match("/^1[3458][0-9]{9}$/",$tel)){    
		return true;
	}
	
	return false;
}

/**
 * 验证输入的邮件地址是否合法
 * @access  public
 * @param   string      $user_email      需要验证的邮件地址
 * @return bool
 */
function isEmail($email)
{
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    if (strpos($email, '@') !== false && strpos($email, '.') !== false){
        if (preg_match($chars, $email)){
            return true;
        }else{
            return false;
        }
    }
	return false;
}
/**
 * 邮件发送函数
 * @param string $to    接收邮件者邮箱
 * @param string $subject 邮件主题 
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
 * @return boolean 
 */
function sendMail($to, $subject = '', $body = '', $attachment = NULL){
	$config = D('WebConfig')->getWebConfig();
	vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
	$mail             = new PHPMailer(); //PHPMailer对象
	$mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
	$mail->IsSMTP();  // 设定使用SMTP服务
	$mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
											 // 2 = messages only
	$mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
	if($config['smtp_port'] == 465){
		$mail->SMTPSecure = 'ssl';              // 使用安全协议
	}

	$mail->Host       = $config['smtp_host'];  // SMTP 服务器
	$mail->Port       = $config['smtp_port'];  // SMTP服务器的端口号
	$mail->Username   = $config['smtp_user'];  // SMTP服务器用户名
	$mail->Password   = $config['smtp_pass'];  // SMTP服务器密码
	$mail->SetFrom($config['smtp_user'], $config['smtp_from_name']);
	$replyEmail       = $config['smtp_user']; //$config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
	$replyName        = $config['smtp_from_name']; //$config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
	$mail->AddReplyTo($replyEmail, $replyName);
	$mail->Subject    = $subject;
	$mail->MsgHTML($body);
	$name = $to;
	$mail->AddAddress($to, $name);
	if(is_array($attachment)){ // 添加附件
		foreach ($attachment as $file){
			is_file($file) && $mail->AddAttachment($file);
		}
	}
	return $mail->Send() ? true : false;//$mail->ErrorInfo;
}
/**
 * 递归创建目录
 * @param string $dirname   目录路径(/a/b/c/)
 * @return boolean 
 */

function markDir($dirname){
	return is_dir($dirname) or (markDir(dirname($dirname)) and mkdir($dirname, 0700));
}

/**
 * 获取指定导航
 * @param string $id    导航的Id
 * @param array $activeUrls 自定义需要选中的分类或导航
 * @return boolean 
 */
function getColumnById($id = 0, $activeUrls = array()){
	if($id == 0){
		return '';
	}else{
		if(!($column = F('nav_'.$id.'_'.MODULE_NAME.'_'.ACTION_NAME.'_'.I('id',0)))){
			$columnObject = D('Column');
			$column = $columnObject->getCateTreeById($id, $activeUrls);
			F('nav_'.$id.'_'.MODULE_NAME.'_'.ACTION_NAME.'_'.I('id',0), $column);
		}
		return $column;
	}
}

#################################################################################


function isStr($str) {
	if (preg_match('/^[a-zA-Z][a-zA-Z0-9-_]*$/', $str)) {
		return true;
	} else {
		return false;
	}
}

function isUrl($url) {
	if (preg_match('/^http(s)?:\/\//i', $url)) {
		return true;
	} else {
		return false;
	}
}

function isDomain($domain) {
	if (preg_match("/^([0-9a-z-]{1,}.)?([0-9a-z-]{1,}.)?[0-9a-z-]{1,}.([0-9a-z-]{1,}.)?[a-z]{2,}$/i", $domain)) {
		return true;
	} else {
		return false;
	}
}

function getUrlContent($url) {
    //require_once(CORE_PATH.'vendor/phpQuery/phpQuery.php');
	vendor('phpQuery.phpQuery'); 
	
	phpQuery::newDocumentFile($url);    

	$data  = array();
	$data['title']       = pq("title")->text();
	$data['keywords']    = pq("meta[name='keywords']")->attr('content');
	$data['description'] = pq("meta[name='description']")->attr('content');
	$charsetGB2312 = pq("meta[charset='gb2312']")->attr('charset');
	$charsetGBK = pq("meta[charset='gbk']")->attr('charset');
	
	$data['keywords']    = empty($data['keywords']) ? pq("meta[name='Keywords']")->attr('content') : $data['keywords'];
	$data['description']    = empty($data['description']) ? pq("meta[name='Description']")->attr('content') : $data['description'];
	
	return $data;
}


/** Baidu Pagerank */
function get_baidu_rank($url) {
	$content = get_web_content("http://mytool.chinaz.com/baidusort.aspx?host=$url");
	if (preg_match('/百度权重：<font color=\"blue\">(\d+)<\/font>/i', $content, $matches)) {
		$rank = intval($matches[1]);
	} else {
		$rank = 0;
	}
	return $rank;
}

/** Google Pagerank */
function get_google_rank($url) {
	import('ORG.Net.PageRank');
	
	$pr = new PageRank();
	$rank = $pr->getGPR($url);
	
	return $rank;
}

/** Sogou Pagerank */
function get_sogou_rank($url) {
	$content = get_web_content("http://rank.ie.sogou.com/sogourank.php?ur=$url");
	if (preg_match('/sogourank=(\d+)/i', $content, $matches)) {
		$rank = intval($matches[1]);
	} else {
		$rank = 0;
	}
	
	return $rank;
}

/** Alexa Rank */
function get_alexa_rank($url) {
	$content = get_web_content("http://xml.alexa.com/data?cli=10&dat=nsa&ver=quirk-searchstatus&url=$url");
	if (preg_match('/<POPULARITY[^>]*URL[^>]*TEXT[^>]*\"([0-9]+)\"/i', $content, $matches)) {
		$rank = strip_tags($matches[1]);
	} else {
		$rank = 0;
	}
	
	return $rank;
}

function get_web_content($url = ''){
	if(empty($url)){
		return '';
	}else{
		return file_get_contents($url);	
	}
}

/** Server IP */
function get_server_ip($url) {
	$domain = get_domain($url);
	if ($domain) {
		$ip = gethostbyname($domain);
	} else {
		$ip = 0;
	}
	
	return $ip;
}

function get_domain($url) {
	if (preg_match("/^(http:\/\/)?([^\/]+)/i", $url, $domain)) {
		return $domain[2];
	} else {
		return false;
	}
}

/*消费记录
action 操作
other  附加项目
*/
function amountLog($action, $other=array()){
	//consumption
	//`id`, `member_id`, `add_time`, `name`, `amount`, `status`, `status_message`
	if($action){
		$config = D('WebConfig')->getWebConfig();
		$memberObject = M('Member');
		$consumptionObject = M('Consumption');
		switch($action){
			case 'submit_websites': //提交网站
				$sessionMemberInfo = session('memberInfo');
				$memberInfo   = $memberObject->where(array('id'=>$sessionMemberInfo['id']))->find();
				$data = array();
				$data['member_id'] = $memberInfo['id'];
				$data['add_time']  = NOW_TIME;
				$data['name']      = '提交网站：'.$other['domain'];
				$data['amount']    = $config['post_website_score'];
				
				if($memberInfo['amount'] >= $config['post_website_score']){
					//1. 扣除会员的余额
					if($memberObject->where(array('id'=>$memberInfo['id']))->setField(array('amount'=>array('exp', 'amount-'.$config['post_website_score'])))){
					//2. 增加一条消费记录
						$data['status'] = 1;
					}else{
						$data['status'] = 2;	
						$data['status_message'] = '扣除会员余额时失败';	
					}	
				}else{
					$data['status'] = 2;	
					$data['status_message'] = '会员余额不足';	
				}
				$consumptionObject->add($data);
			break;
		}
	}
	//这里可以记录一下非法操作的action
}